<template>
  <div>
    <el-card class="box-card" shadow="always" style="margin:1px;" :body-style="bodyStyle">
      <div slot="header">
        <span>角色设置</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="headerOperation">
        <div style="float:left;margin-left:10px;">
          <el-input v-model="searchKey" placeholder="请输入你要查找的内容" style="width:200px;margin-right:10px;" />
          <el-button icon="el-icon-search" type="primary" @click="handleFilter" @keyup.enter.native="handleFilter">筛选</el-button>
        </div>
        <div style="float:right;margin-right:10px;">
          <el-button icon="el-icon-edit" type="primary" @click="handleAdd">添加</el-button>
          <el-button icon="el-icon-refresh" type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </div>
    </el-card>
    <div>
      <el-table :data="roleList">
        <el-table-column label="Id" prop="id" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="描述" prop="description" />
        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="{row,$index}">
            <el-button size="mini" type="primary" @click="handleEdit(row,$index)">编辑</el-button>
            <el-button size="mini" type="primary" @click="handlePermissionEdit(row,$index)">权限</el-button>
            <el-button size="mini" type="danger" @click="handleDel(row.id,$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="角色信息" :visible.sync="dialogFormVisible" @close="handleDialogClose">
        <el-form ref="formDialog" :model="formData">
          <!-- <el-form-item label="id" prop="id" :label-width="lableWidth">
            <el-input v-model="formData.id" class="inputWidth" />
          </el-form-item> -->
          <el-form-item label="角色名称" prop="roleName" :label-width="lableWidth">
            <el-input v-model="formData.roleName" class="inputWidth" />
          </el-form-item>
          <el-form-item label="描述" prop="description" :label-width="lableWidth">
            <el-input v-model="formData.description" class="inputWidth" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleFormCancel">取 消</el-button>
          <el-button type="primary" @click="handleFormConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="权限" :visible.sync="dialogPermissionFormVisible" @close="handleDialogClose">
        <el-tree
          ref="permissionTree"
          :props="permissionProp"
          :data="permissionList"
          show-checkbox
          node-key="name"
          :default-checked-keys="defaultCheckedKeys"
        />
        <div slot="footer" class="dialog-footer">
          <el-button @click="handlePermissionFormCancel">取 消</el-button>
          <el-button type="primary" @click="handlePermissionFormConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoles, saveRolePermission, addRoles, updateRoles, deleteRoles } from '@/api/role'
// import routes from '@/router/routes'
import { getAllMenuFromRoutes } from '@/utils/access'
export default {
  data() {
    return {
      roleList: [],
      searchKey: '',
      dialogFormVisible: false,
      dialogPermissionFormVisible: false,
      isAddBtnClick: true,
      lableWidth: '20%',
      currentIndex: -1,
      formData: {
        id: 0,
        roleName: '',
        access: [],
        description: '',
        remarks: ''
      },
      formPermissionData: {
        id: 0,
        roleName: '',
        access: [],
        description: '',
        remarks: ''
      },
      permissionProp: {
        label: 'title',
        children: 'children'
      },
      defaultCheckedKeys: [],
      bodyStyle: {
        padding: '0px'
      }
    }
  },
  // 计算属性，获取待编辑角色权限
  computed: {
    permissionList: function() {
      return getAllMenuFromRoutes()
    }
  },
  created: function() {
    // this.fetchList()
    this.roleList = this.fetchList()
  },
  methods: {
    fetchList: function() {
      getRoles().then(res => {
        // console.log(res)
        this.roleList = res.data
      })
    },
    handleFilter: function() {
      // console.log(this.searchKey)
      var originList = this.roleList
      var list = originList.filter(item => item.roleName.indexOf(this.searchKey) >= 0)
      this.roleList = list
    },
    handleAdd: function() {
      // this.resetFormFields()
      this.dialogFormVisible = true
      this.isAddBtnClick = true
    },
    handleRefresh: function() {
      this.fetchList()
      this.$message.success('刷新成功！')
    },
    handleEdit: function(item, index) {
      this.currentIndex = index
      this.dialogFormVisible = true
      // 编辑的时候，给form赋值需要延后执行，否则重置表单将不生效
      this.$nextTick(() => {
        this.formData = Object.assign({}, item)
      })
      this.isAddBtnClick = false
    },
    handlePermissionEdit(item, index) {
      this.currentIndex = index
      this.dialogPermissionFormVisible = true
      this.$nextTick(() => {
        this.formPermissionData = Object.assign({}, item)
        // 设置默认选中的keys，在连续点击的时候，会失效，所以改成如下方法，问题解决；并且需要在下一次事件发生时调用
        // this.defaultCheckedKeys = item.access
        var accessArr = item.access || []
        this.$refs.permissionTree.setCheckedKeys(accessArr)
      })
    },
    // 角色删除
    handleDel: function(id, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRoles(id).then(res => {
          this.roleList.splice(index, 1)
          this.$message.success('删除成功!')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 角色弹出框取消按钮点击事件
    handleFormCancel: function() {
      this.dialogFormVisible = false
      // this.$refs[formName].resetFields()
    },
    // 角色弹出框确定按钮点击事件
    handleFormConfirm: function() {
      this.dialogFormVisible = false
      var temp = Object.assign({}, this.formData)
      // this.$refs[formName].resetFields()
      if (this.isAddBtnClick) {
        addRoles(temp).then(res => {
          this.roleList.push(res.data)
          this.$message.success('增加成功！')
        })
      } else {
        updateRoles(temp.id, temp).then(res => {
          this.roleList.splice(this.currentIndex, 1, res.data)
          this.$message.success('修改成功！')
        })
      }
    },
    // 角色权限弹出框关闭按钮点击事件
    handlePermissionFormCancel: function() {
      this.dialogPermissionFormVisible = false
    },
    // 角色权限弹出框确定按钮点击事件
    handlePermissionFormConfirm: function() {
      var roleId = this.formPermissionData.id
      var accessList = this.$refs.permissionTree.getCheckedNodes()
      var arr = []
      accessList.forEach(item => {
        var row = {
          title: item.title,
          name: item.name
        }
        arr.push(row)
      })

      saveRolePermission(roleId, arr).then(res => {
        this.roleList.splice(this.currentIndex, 1, res.data)
        this.$message.success(res.msg)
      })
      this.dialogPermissionFormVisible = false
    },
    // 对话窗口关闭时 重置表单项
    handleDialogClose: function() {
      this.resetFormFields()
    },
    resetFormFields() {
      var formDialog = this.$refs.formDialog
      var formPermissionDialog = this.$refs.permissionTree
      if (formDialog) {
        formDialog.resetFields()
      }
      if (formPermissionDialog) {
        formPermissionDialog.setCheckedKeys([])
      }
    }
  }
}
</script>

